package com.wedimob.slideshare.task.io.disk;

import java.net.URI;

import com.wedimob.slideshare.RuntimeConfig;

public class PathHelper {

    private static String _buildPath(String... paths) {
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paths.length; i++) {
                if (i > 0)
                    sb.append("/");
                sb.append(normalizePath(paths[i]));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static URI buildFileOrDir(String dir, String filename, String... paths) {
        try {
            return new URI(
                    ("file:///"
                            + RuntimeConfig.getInstance().getRootpath().replace("\\", "/").replace(" ", "%20")
                            + "/" + dir
                            + (paths != null && paths.length > 0 ? "/" + _buildPath(paths) : "")
                            + (filename == null ? "" : "/" + normalizePath(filename))).replace("\\", "/"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static URI buildOutputFile(String filename, String... paths) {
        return buildFileOrDir(RuntimeConfig.getInstance().getOutputdir(), filename, paths);
    }

    public static URI buildOutputPath(String... paths) {
        return buildFileOrDir(RuntimeConfig.getInstance().getOutputdir(), null, paths);
    }

    public static URI buildPath(URI path, String filename) {
        try {
            return new URI(path.toString() + "/" + filename);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static URI buildTmpFile(String filename, String... paths) {
        return buildFileOrDir(RuntimeConfig.getInstance().getTmpdir(), filename, paths);
    }

    public static URI buildTmpPath(String... paths) {
        return buildFileOrDir(RuntimeConfig.getInstance().getTmpdir(), null, paths);
    }

    protected static String normalizePath(String str) {
        if (str == null)
            return "undefined";
        String result = str
                .replace("\t", " ")
                .replace("/", "_")
                .replace(",", "")
                .replace(";", "")
                .replace("=", "")
                .replace("*", "")
                .replace("!", "")
                .replace(":", "")
                .replace("|", "")
                .replace("#", "_")
                .replace("?", " ")
                .replace(" ", "%20")
                .trim();
        return result;
    }

}
